package handler

import (
	"crypto"
	_ "crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"gitcode.net/togolife/nfttoken/common"
	"gitcode.net/togolife/nfttoken/account"
)

type CreateAccountInput struct {
	Sign string `json:"sign"`
}

type CreateAccountOutput struct {
	RetCode int    `json:"retCode"`
	RetMsg  string `json:"retMsg"`
	Account string `json:"account,omitempty"`
}

func CreateAccountRet(w http.ResponseWriter, out *CreateAccountOutput) {
	v, err := json.Marshal(out)
	if err != nil {
		return
	}
	w.Write(v)
}

func setCreateAccountOutput(out *CreateAccountOutput, err common.NftError) {
	out.RetCode = err.ErrorNo
	out.RetMsg = err.ErrorMsg
}

func (input *CreateAccountInput) checkSign() bool {
	s := "sign=" + hdConf.SignRandomKey
	m := crypto.SHA256.New()
	m.Write([]byte(s))
	v := hex.EncodeToString(m.Sum(nil))
	return v == input.Sign
}

func CreateAccountIf(w http.ResponseWriter, req *http.Request) {
	input := CreateAccountInput{}
	output := CreateAccountOutput{}
	defer CreateAccountRet(w, &output)
	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		hdLog.LogE("Read CreateAccount http request body failed! [%v]", err)
		setCreateAccountOutput(&output, common.NewError(400))
		return
	}
	err = json.Unmarshal(body, &input)
	if err != nil {
		hdLog.LogE("Decode CreateAccount http request body failed! [%v]", err)
		setCreateAccountOutput(&output, common.NewError(400))
		return
	}
	if !input.checkSign() {
		hdLog.LogE("Check input sign failed!")
		setCreateAccountOutput(&output, common.NewError(401))
		return
	}
	output.Account, err = account.CreateAccount()
	if err != nil {
		hdLog.LogE("CreateAccount failed [%v]", err)
		setCreateAccountOutput(&output, common.NewError(507))
		return
	}
	setCreateAccountOutput(&output, common.NewError(200))
	return
}
